import React, { useState, useEffect } from 'react';
import AppBar from '@material-ui/core/AppBar';
import Toolbar from '@material-ui/core/Toolbar';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import InputBase from '@material-ui/core/InputBase';
import { createStyles, fade, Theme, makeStyles } from '@material-ui/core/styles';
import MenuIcon from '@material-ui/icons/Menu';
import SearchIcon from '@material-ui/icons/Search';
import { Container } from '@material-ui/core';
import { useRefState } from '../../utils/hooks'
import Nav from './Nav'
import ScrollTop from './ScrollTop'
import KeyboardArrowUpIcon from '@material-ui/icons/KeyboardArrowUp';
import Brightness4Icon from '@material-ui/icons/Brightness4';
import BrightnessHighIcon from '@material-ui/icons/BrightnessHigh';
import Logo from '../logo'
import Link from 'next/link';
import useDawer from './useDawer'

const useStyles = makeStyles((theme: Theme) =>
  createStyles({
    root: {
      flexGrow: 1
    },
    mobileButton: {
      display: 'none',
      [theme.breakpoints.down('sm')]: {
        display: 'block'
      }
    },
    menuButton: {
      margin: theme.spacing(0, 2),
    },
    title: {
      [theme.breakpoints.down('sm')]: {
        display: 'none'
      }
    },
    nav: {
      marginLeft: theme.spacing(10),
      '& .MuiTab-root': {
        minWidth: 'initial',
        padding: theme.spacing(0, 2)
      },
      [theme.breakpoints.down('sm')]: {
        display: 'none'
      }
      // '& .MuiTab-wrapper>a': {
      //   color: theme.palette.primary,
      //   opacity: 0.5,
      //   transition: '0.15s',
      //   textDecoration: 'none',
      //   '&:hover': {
      //     opacity: 1
      //   }
      // }
    },
    search: {
      display: 'none',
      position: 'relative',
      borderRadius: theme.shape.borderRadius,
      backgroundColor: fade(theme.palette.common.white, 0.15),
      '&:hover': {
        backgroundColor: fade(theme.palette.common.white, 0.25),
      },
      marginLeft: 0,
      width: '100%',
      [theme.breakpoints.up('sm')]: {
        marginLeft: theme.spacing(1),
        width: 'auto',
      },
    },
    searchIcon: {
      padding: theme.spacing(0, 2),
      height: '100%',
      position: 'absolute',
      pointerEvents: 'none',
      display: 'flex',
      alignItems: 'center',
      justifyContent: 'center',
    },
    inputRoot: {
      color: 'inherit',
    },
    inputInput: {
      padding: theme.spacing(1, 1, 1, 0),
      // vertical padding + font size from searchIcon
      paddingLeft: `calc(1em + ${theme.spacing(4)}px)`,
      transition: theme.transitions.create('width'),
      width: '100%',
      [theme.breakpoints.up('sm')]: {
        width: '12ch',
        '&:focus': {
          width: '20ch',
        },
      },
    },
    colorBtn: {
      position: 'absolute',
      right: theme.spacing(3)
    }
  }),
);

export default function SearchAppBar({ title }) {
  const classes = useStyles();
  const [themeType, setThemeType] = useState('light')
  const [dawer, open, setOpen] = useDawer()
  useEffect(() => {
    function onThemeChange() {
      setThemeType(localStorage.getItem('themeType') as ThemeTypes)
    }
    window.addEventListener('$themeChange', onThemeChange)
    return function () {
      window.removeEventListener('$themeChange', onThemeChange)
    }
  }, [])

  return (
    <div className={classes.root}>
      {/* 抽屉 */}
      {dawer}
      <AppBar color='default' position="static">
        <Title title={title} >
          <Toolbar disableGutters variant='dense'>
            <IconButton
              edge="start"
              className={classes.menuButton + ' ' + classes.mobileButton}
              color="inherit"
              aria-label="open drawer"
              onClick={() => setOpen(true)}
            >
              <MenuIcon />
            </IconButton>
            <Typography className={classes.title} variant="h6" noWrap>
              <Link href='/'>
                <a>
                  <Logo title='Boboan' />
                </a>
              </Link>
            </Typography>
            <div className={classes.nav}>
              <Nav />
            </div>

            <div className={classes.search}>
              <div className={classes.searchIcon}>
                <SearchIcon />
              </div>
              <InputBase
                placeholder="站内搜索"
                classes={{
                  root: classes.inputRoot,
                  input: classes.inputInput,
                }}
                inputProps={{ 'aria-label': 'search' }}
              />
            </div>
            <IconButton
              edge="start"
              className={classes.colorBtn}
              color="inherit"
              aria-label="open drawer"
              onClick={() => {
                window.setTheme(themeType === 'light' ? 'dark' : 'light')
              }}
            >
              {
                themeType === 'light'
                  ? <Brightness4Icon />
                  : <BrightnessHighIcon />
              }
            </IconButton>
          </Toolbar>
        </Title>
      </AppBar>
    </div>
  );
}

const useTitleStyles = makeStyles((theme: Theme) =>
  createStyles({
    scrollTitle: {
      padding: '0 24px',
      position: 'relative',
      height: 'fit-content',
      width: '100%',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      overflow: 'hidden'
    },
    appbar: {
      width: '100%',
      transition: '0.3s',
      '&.hide': {
        transform: 'translateY(-48px)'
      }
    },
    title: {
      position: 'absolute',
      color: theme.palette.text.primary,
      fontSize: '22px',
      transformOrigin: 'bottom',
      transition: '0.3s',
      transform: 'translateY(48px)',
      transformStyle: 'preserve-3d',
      '&.show': {
        color: theme.palette.text.primary,
        transformOrigin: 'bottom',
        transform: 'translateY(0px)'
      }
    },
    upIcon: {}
  }),
);
function Title({ title, children }) {
  const [show, showRef, setShow] = useRefState(false)
  const classes = useTitleStyles();
  useEffect(() => {
    function onScroll(e) {
      const h1 = document.getElementById('titleH1')
      if (!h1) {
        return
      }
      const { height, top } = h1.getBoundingClientRect()
      const should = window.pageYOffset > height + top
      if (showRef.current && !should) {
        setShow(false)
      }
      if (!showRef.current && should) {
        setShow(true)
      }
    }
    window.addEventListener('scroll', onScroll)
    return () => {
      window.removeEventListener('scroll', onScroll)
    }
  }, [])
  return <Container className={classes.scrollTitle} maxWidth='lg' disableGutters>
    <div className={`${classes.appbar} ${show ? 'hide' : ''}`}>{children}</div>
    <h3 className={`${classes.title} ${show ? 'show' : ''}`}> {title} </h3>
    <ScrollTop window={() => global ? undefined : window}>
      <IconButton
        edge="start"
        className={classes.upIcon}
        color="inherit"
        aria-label="open drawer"
      >
        <KeyboardArrowUpIcon />
      </IconButton>
    </ScrollTop>
  </Container>
}
